package org.dxy.domain.handler.productionLine;

import com.google.common.eventbus.EventBus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.handler.CommandHandler;
import org.dxy.domain.port.repository.IProductionLineRepository;
import org.dxy.domain.port.repository.IWorkstationRepository;
import org.dxy.domain.command.productionLine.RemoveWorkstationFromLineCommand;
import org.dxy.domain.model.aggregate.ProductionLine;
import org.dxy.domain.model.aggregate.Workstation;
import org.dxy.types.common.CommandResult;
import org.springframework.stereotype.Component;

/**
 * @description: 移除工作站从产线命令处理器
 * @author: dxy
 * @createTime: 2025/6/26 10:30
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RemoveWorkstationFromLineCommandHandler implements CommandHandler<RemoveWorkstationFromLineCommand, Void> {

    private final IProductionLineRepository productionLineRepository;
    private final IWorkstationRepository workstationRepository;
    private final EventBus eventBus;

    @Override
    public CommandResult<Void> handle(RemoveWorkstationFromLineCommand command) {
        ProductionLine line = productionLineRepository.findById(command.getLineId());
        if (line == null) {
            log.error("未找到产线，command={}", command);
            return CommandResult.fail("产线不存在");
        }

        try {

            // 2. 加载工位实体
            Workstation workstation = workstationRepository.findById(command.getWorkstationId());
            if (workstation == null) {
                log.error("未找到产线，command={}", command);
                return CommandResult.fail("产线不存在");
            }



            // 4. 调用聚合根移除工位方法（内部会添加事件到事件列表）
            line.removeWorkstation(command, workstation);

            // 5. 持久化变更
            productionLineRepository.save(line);
            workstationRepository.save(workstation);

            // 6. 发布聚合产生的所有事件
            line.getDomainEvents().forEach(eventBus::post);

            // 7. 清理事件，防止重复发布
            line.clearDomainEvents();
            
            log.info("移除工作站从产线成功, command={}", command);
            return CommandResult.success("移除工作站从产线成功");
        } catch (IllegalStateException e) {
            log.warn("移除工作站从产线失败，原因：{}", e.getMessage());
            return CommandResult.fail(e.getMessage());
        }
    }

} 